<template>
  <div class="search-input" @touchstart="focus">
    <div class="icons-search icon"></div>
    <div class="input-wrapper">
      <input ref="input" type="search" class="input" v-model="keyword" :placeholder="placeholder" maxlength="20" />
      <div class="clear-btn" v-if="showClear && !!keyword" @click="clear">
        <i class="icons-close btn-icon"></i>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String
    },
    placeholder: {
      type: String,
      default: '请输入查询关键字'
    },
    showClear: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keyword: ''
    }
  },
  methods: {
    focus() {
      setTimeout(() => {
        this.$refs.input.focus()
      }, 100)
    },
    clear() {
      this.keyword = ''
    }
  },
  watch: {
    keyword(newVal) {
      this.$emit('input', newVal)
    },
    value(val) {
      this.keyword = val
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-input {
    flex-grow: 1;
    height: 35px;
    display: flex;
    background-color: white;
    border: solid 1px rgb(224, 224, 224);
    border-radius: 2px;
    align-self: center;

    .icon {
      height: 100%;
      margin-left: 20px;
      margin-right: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      &::before{
        font-size: 16px;
        color: #C1C1C1;
      }
    }

    .input-wrapper {
      flex-grow: 1;
      height: 100%;
      display: flex;

      .input {
        flex-grow: 1;
        height: 100%;
        background-color: transparent;
        border: none;
      }

      .clear-btn {
        width: 32px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .btn-icon {
          color: #C1C1C1;
          font-size: 12px;
        }
      }
    }
  }
</style>